package com.example.administrator.capital.mine;


import android.Manifest;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.administrator.capital.R;
import com.example.administrator.capital.base.BaseBackFragment;
import com.example.administrator.capital.eventbus.EventBase;
import com.example.administrator.capital.login.LoginActivity;
import com.example.administrator.capital.mine.second.AmendNickNameFragment;
import com.example.administrator.capital.mine.second.BindCardFragment;
import com.example.administrator.capital.mine.second.BindPhoneFragment;
import com.example.administrator.capital.mine.second.CertificationFragment;
import com.example.administrator.capital.mine.second.SetDealPasswordFragment;
import com.example.administrator.capital.mine.second.UpdatePasswordFragment;
import com.example.administrator.capital.model.MineModel;
import com.example.administrator.capital.model.bean.OneMemBean;
import com.example.administrator.capital.presenter.MinePresenter;
import com.example.administrator.capital.presenter.base.IViewRequest;
import com.example.administrator.capital.utils.CacheUtil;
import com.example.administrator.capital.utils.JsonUtils;
import com.example.administrator.capital.utils.PreferenceManager;
import com.example.administrator.capital.utils.ToastUtil;
import com.example.administrator.capital.widget.SingleChoiceDialog;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.lzy.okgo.model.Response;
import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;
import com.sunfusheng.glideimageview.GlideImageView;

import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import eventbusactivityscope.EventBusActivityScope;

/**
 * A simple {@link Fragment} subclass.
 * 账户设置
 */
public class AccountSettingFragment extends BaseBackFragment implements TakePhoto.TakeResultListener, InvokeListener {
    @BindView(R.id.user_pic)
    GlideImageView mUserPic;
    Unbinder unbinder;
    @BindView(R.id.nick_name)
    RelativeLayout mNickName;
    @BindView(R.id.phone)
    RelativeLayout mPhone;
    @BindView(R.id.certification)
    RelativeLayout mCertification;
    @BindView(R.id.bind_card)
    RelativeLayout mBindCard;
    @BindView(R.id.update_password)
    RelativeLayout mUpdatePassword;
    @BindView(R.id.set_deal_password)
    RelativeLayout mSetDealPassword;
    @BindView(R.id.clear_cache)
    RelativeLayout mClearCache;
    @BindView(R.id.exit)
    Button mExit;
    @BindView(R.id.imageView)
    ImageView mImageView;
    @BindView(R.id.tv_cache)
    TextView mTvCache;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_chek)
    TextView tvChek;
    @BindView(R.id.tv_bind_bank)
    TextView tvBindBank;
    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private TextView mBack;
    private ProgressDialog mProgressDialog;
    private MinePresenter mMinePresenter;

    public AccountSettingFragment() {
        // Required empty public constructor
    }

    public static AccountSettingFragment newInstance() {

        Bundle args = new Bundle();
        AccountSettingFragment fragment = new AccountSettingFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_account_setting, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        EventBusActivityScope.getDefault(_mActivity).register(this);
        mBack = view.findViewById(R.id.app_title_back);
        mProgressDialog = new ProgressDialog(getContext());
        mProgressDialog.setMessage("加载中……");
        mMinePresenter=new MinePresenter(null);
        postDate(PreferenceManager.instance().getUseId());
    }

    @Override
    protected void setListener() {
        super.setListener();
        mUserPic.setOnClickListener(this);
        mPhone.setOnClickListener(this);
        mNickName.setOnClickListener(this);
        mCertification.setOnClickListener(this);
        mBindCard.setOnClickListener(this);
        mUpdatePassword.setOnClickListener(this);
        mSetDealPassword.setOnClickListener(this);
        mClearCache.setOnClickListener(this);
        mExit.setOnClickListener(this);
        mClearCache.setOnClickListener(this);
        mBack.setOnClickListener(this);
    }

    private void postDate(String uid) {
        mMinePresenter.oneMem(new IViewRequest<String>() {
            @Override
            public void onFailMsg(String var) {
                if (var.equals("请登录")) {
                    mBaseActivity.showActivity(LoginActivity.class,null);
                } else {
                    ToastUtil.showShort(var);
                }
            }

            @Override
            public void onCode(int code) {
                ToastUtil.showShort(code);
            }

            @Override
            public void onSuccess(Response<String> data) {
                OneMemBean bean = JsonUtils.parse(data.body(), OneMemBean.class);
                tvName.setText(bean.getData().getUsername());
                tvChek.setText(bean.getData().getRealname());
                tvPhone.setText(bean.getData().getTel());
            }
            @Override
            public void onFail(Response<String> error) {

            }
        }, uid);
    }
        @Override
    protected void setData() {
        super.setData();
        setSize();
        postDate(PreferenceManager.instance().getUseId());
    }

    /**
     * 显示缓存大小
     */
    private void setSize() {
        try {
            String size = CacheUtil.getTotalCacheSize(getContext());
            mTvCache.setText(size);
        } catch (Exception e) {
            e.printStackTrace();
            mTvCache.setText("0B");
        }
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.user_pic:
                avatar();
                break;
            case R.id.phone:
                start(BindPhoneFragment.newInstance());
                break;
            case R.id.nick_name:
                start(AmendNickNameFragment.newInstance());
                break;
            case R.id.certification:
                start(CertificationFragment.newInstance());
                break;
            case R.id.bind_card:
                start(BindCardFragment.newInstance());
                break;
            case R.id.update_password:
                start(UpdatePasswordFragment.newInstance());
                break;
            case R.id.set_deal_password:
                start(SetDealPasswordFragment.newInstance());
                break;
            case R.id.exit:
                PreferenceManager.instance().removeToken();
                showActivity(LoginActivity.class);
                mBaseActivity.finish();
                break;
            case R.id.clear_cache:
                cleanCache();
                break;
            case R.id.app_title_back:
                _mActivity.onBackPressed();
                break;
        }
    }
    /**
     * 清理缓存
     */
    private void cleanCache() {
        mProgressDialog.show();
        Acp.getInstance(getActivity()).request(new AcpOptions.Builder().setPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE).build(), new AcpListener() {
            @Override
            public void onGranted() {
                mProgressDialog.dismiss();
                ToastUtil.showShort("清理成功！");
                CacheUtil.clearAllCache(getContext());
                setSize();
            }

            @Override
            public void onDenied(List<String> permissions) {
                mProgressDialog.dismiss();
                ToastUtil.showShort(permissions.toString() + "权限被拒绝，请允许应用获取权限");
            }
        });
    }

    /**
     * 设置头像
     */
    private void avatar() {
        List<String> list = new ArrayList<>();
        list.add("拍照");
        list.add("相册");
        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        final Uri imageUri = Uri.fromFile(file);
        final CropOptions cropOptions = new CropOptions.Builder().setAspectX(1).setAspectY(1).setWithOwnCrop(true).create();
        new SingleChoiceDialog.Builder(getContext()).addList(list)
                .setTitle("请选择")
                .setOnItemClickListener(new SingleChoiceDialog.OnItemClickListener() {
                    @Override
                    public void OnItemClick(String title, int position) {
                        if (position == 0) {//拍照
                            takePhoto.onPickFromCaptureWithCrop(imageUri, cropOptions);
                        } else if (position == 1) {//相册
                            takePhoto.onPickFromGalleryWithCrop(imageUri, cropOptions);
                        }
                    }
                }).show();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
    @Subscribe
    public void onTabSelectedEvent(EventBase event) {
        if (event.getName().equals("刷新界面")) {
            postDate(PreferenceManager.instance().getUseId());
        }
    }
    @Override
    public void takeSuccess(TResult result) {
        mUserPic.loadLocalCircleImage(result.getImage().getOriginalPath(), R.drawable.mine_icon);
    }

    @Override
    public void takeFail(TResult result, String msg) {
        ToastUtil.showShort(msg);
    }

    @Override
    public void takeCancel() {
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //以下代码为处理Android6.0、7.0动态权限所需
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(getActivity(), type, invokeParam, this);
    }

}
